//
// Created by yyl on 2018/6/6.
//

#ifndef MYMUSIC_YAUDIO_H
#define MYMUSIC_YAUDIO_H

#include "YQueue.h"
#include "CallJava.h"
#include <SLES/OpenSLES.h>
#include <SLES/OpenSLES_Android.h>
#include "yyl_ffmpeg.h"
#include "SoundTouch.h"

using namespace soundtouch;


class YAudio {
public:
    CallJava *callJava = NULL;
    int streamIndex = -1;
    AVCodecParameters *avCodecParameters = NULL;
    AVCodecContext *avCodecContext = NULL;
    YQueue *queue = NULL;
    PlayStatus *playStatus = NULL;
    pthread_t threadPlay;
    AVPacket *avPacket = NULL;
    AVFrame *avFrame = NULL;
    int result = 0;
    uint8_t *buffer = NULL;//音频流数据
    int data_size = 0;


    int sample_rate = 0;
    bool isRecord = false;
    int64_t duration = 0;
    double clock=0;//总的播放时长
    double now_time=0;//当前frame时间
    double last_time=0; //上一次调用时间
    bool readFrameFinished = false;
    AVRational time_base;
    pthread_mutex_t codecMutexLock;

    // 引擎接口
    SLObjectItf engineObject = NULL;
    SLEngineItf engineEngine = NULL;

//混音器
    SLObjectItf outputMixObject = NULL;
    SLEnvironmentalReverbItf outputMixEnvironmentalReverb = NULL;
    SLEnvironmentalReverbSettings reverbSettings = SL_I3DL2_ENVIRONMENT_PRESET_STONECORRIDOR;


//pcm
    SLObjectItf pcmPlayerObject = NULL;
    SLPlayItf pcmPlayerPlay = NULL;
    SLVolumeItf pcmVolumePlay = NULL;

    SLMuteSoloItf pcmMuteSolo = NULL;

//缓冲器队列接口
    SLAndroidSimpleBufferQueueItf pcmBufferQueue = NULL;
    int volumePercent = 100;
    int muteType = 2;

    SoundTouch *soundTouch = NULL;
    SAMPLETYPE *sampletypeBuffer = NULL;
    bool isFinished = true;
    uint8_t *out_buffer;
    int channelnb = 0;//通道数
    int numCount = 0;//采样个数
    float mPitch = 1.0f;//音调
    float mSpeed = 1.0f;//音速


public:
    YAudio(PlayStatus *playStatus, int sample_rate, CallJava *callJava);

    ~YAudio();

    void play();

    int resampleAudio(void **pcmbuf);

    void initOpenSLES();

    int getCurrentSampleRateForOpenSLES(int sample_rate);


    int changePlayState(bool isPlay);

    void stop();

    void release();

    int getSoundTouchData();

    void setVolume(int percent);

    void setMute(int mute);

    void setSpeed(double speed);

    void setPitch(double pitch);

    int getPCMDB(char *pcmcata, size_t pcmsize);


};


#endif //MYMUSIC_YAUDIO_H
